package typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Address;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: hbliy
 * @date: 2025/2/14 12:32
 */
public class AddressTypeHandler extends BaseTypeHandler<Address> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Address parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (Exception e) {
            throw new SQLException("Error converting Address to String", e);
        }
    }

    @Override
    public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseAddress(rs.getString(columnName));
    }

    @Override
    public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseAddress(rs.getString(columnIndex));
    }

    @Override
    public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseAddress(cs.getString(columnIndex));
    }

    private Address parseAddress(String json) throws SQLException {
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, Address.class);
        } catch (Exception e) {
            throw new SQLException("Error converting String to Address", e);
        }
    }
}
